<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Sms;

use App\Service\BaseService;
use Exception;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\EasySms;

class SmsService extends BaseService
{
    public function SendSms($telephone)
    {
        $key = sprintf('SMS_%s', $telephone);
        $ttl = $key . '_ttl';
        if (Cache::has($ttl)) {
            return false;
        }
//        if (env('APP_DEBUG')) {
//            $content = 123456;
//        } else {
        $content = rand(1000, 9999);
//        }
        //TODO 发送逻辑
        if ($this->smsRealization($telephone, $content)) {
            Cache::put($ttl, 1, now()->addMinute());
            Cache::put($key, $content, now()->addMinutes(5));
        }
        return true;
    }

    public function getSms($telephone)
    {
        $key = sprintf('SMS_%s', $telephone);
        return Cache::get($key);
    }

    public function smsRealization($telephone, $content)
    {
        $sms = new EasySms(config('sms'));
        try {
            $res = $sms->send($telephone, [
                'content' => "您的验证码为：{$content}，请勿泄露于他人！",
                'template' => 'SMS_320180798',
                'data' => [
                    'code' => $content,
                ],
            ]);
        } catch (Exception $e) {
            $this->Log($e, '短信发送失败');
        }

        return true;
    }
}
